<template>
  <button
    ref="buttonRef"
    v-bind="attrs"
    :class="buttonClass"
    :disabled="actualDisabled"
    :style="buttonStyle"
    @click="handleClick"
    @dblclick="handleDoubleClick"
    @mousedown.stop
  >
    <!-- 图标+文字模式 -->
    <div v-if="showLabelValue" class="toolbar-button-with-label">
      <div v-if="icon" :class="iconClass" class="toolbar-button-icon" :style="iconStyle" />
      <span v-else-if="$slots.icon" class="toolbar-button-icon" :style="iconStyle">
        <slot name="icon" />
      </span>
      <span v-if="labelText" class="toolbar-button-label">{{ labelText }}</span>
    </div>
    <!-- 纯图标模式 -->
    <template v-else>
      <div v-if="icon" :class="iconClass" class="toolbar-button-icon" :style="iconStyle" />
      <span v-else-if="$slots.icon" class="toolbar-button-icon" :style="iconStyle">
        <slot name="icon" />
      </span>
      <slot v-else />
    </template>
  </button>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  onBeforeUnmount,
  ref,
  watch,
  useAttrs,
  nextTick,
  inject,
} from "vue";
import tippy, { type Instance as TippyInstance } from "tippy.js";
import "tippy.js/dist/tippy.css";
import type { Editor } from "@tiptap/core";
import type { ButtonProps } from "./button.types";
import type { EditorProps } from "../../../types";
import { useState } from "../../../store";

defineOptions({
  inheritAttrs: false,
  name: "ToolbarButton",
});

const props = withDefaults(defineProps<ButtonProps>(), {
  disabled: false,
  active: false,
  variant: "default",
  round: false,
  circle: false,
  hideText: true,
  largeIcon: false,
});

const emit = defineEmits<{
  (e: "click", event: MouseEvent): void;
  (e: "dblclick", event: MouseEvent): void;
}>();

const attrs = useAttrs();
const buttonRef = ref<HTMLButtonElement>();
let buttonTippyInstance: TippyInstance | null = null;
let themeObserver: MutationObserver | null = null;

// 注入编辑器实例
const editor = inject<{ value: Editor | null } | null>("editor", null);

// 计算实际禁用状态（考虑 editor.isEditable）
const actualDisabled = computed(() => {
  if (props.disabled) return true;
  if (editor?.value && !editor.value.isEditable) return true;
  return false;
});

// 格式化快捷键显示
const formatShortcut = (shortcut: string): string => {
  return shortcut.replace(/([A-Z])/g, " $1").replace(/\s+/g, " ").trim();
};

// 计算 tooltip 内容
const tooltipContent = computed(() => {
  if (props.tooltip) return props.tooltip;
  
  const title = props.title || "";
  const shortcut = props.shortcut ? formatShortcut(props.shortcut) : "";
  
  return title && shortcut ? `${title} (${shortcut})` : title || shortcut;
});

// tooltip 标题（用于向后兼容）
const titleValue = computed(() => {
  return tooltipContent.value || (props.title || (attrs.title as string | undefined));
});

// 判断是否显示标签（基于 title 是否存在，且未隐藏文本）
// hideText 默认为 true，所以只有当 hideText 明确为 false 时才显示标签
const showLabelValue = computed(() => {
  // 如果 hideText 为 true（默认值），则不显示标签
  if (props.hideText === true) return false;
  // 如果 hideText 为 false，且 title 存在，则显示标签
  if (props.hideText === false) return !!props.title;
  // 如果 hideText 为 undefined（不应该发生，因为 withDefaults 设置了默认值），默认隐藏
  return false;
});

// 注入编辑器配置
const injectedEditorProps = inject<EditorProps | undefined>("editorProps");
const toolbarState = injectedEditorProps ? useState("toolbar", { value: injectedEditorProps }) : null;

// 计算布局方向：ribbon 模式为上下，simple 模式为左右
const isVerticalLayout = computed(() => {
  const mode = toolbarState?.value?.mode;
  return mode === "ribbon" || (!mode || (mode !== "simple" && mode !== "ribbon"));
});

// label 文本
const labelText = computed(() => {
  if (!showLabelValue.value) return "";
  return props.title || "";
});

const buttonClass = computed(() => {
  const classes = ["toolbar-button", "flex", "items-center", "justify-center"];
  
  if (props.active) classes.push("is-active");
  if (actualDisabled.value) classes.push("is-disabled");
  if (showLabelValue.value) {
    classes.push("has-label", isVerticalLayout.value ? "label-vertical" : "label-horizontal");
  }
  if (props.largeIcon) classes.push("is-large-icon");
  
  return classes.join(" ");
});

const buttonStyle = computed(() => {
  const style: Record<string, string> = {
    border: "none",
    boxShadow: "none",
    outline: "none",
  };

  if (props.circle) {
    style.borderRadius = "50%";
  } else if (props.round) {
    style.borderRadius = "20px";
  }

  return style;
});

// 计算图标尺寸（大图标 24px，普通图标 20px）
const iconSize = computed(() => props.largeIcon ? "24px" : "20px");

const iconStyle = computed(() => ({
  width: iconSize.value,
  height: iconSize.value,
  fontSize: iconSize.value,
  lineHeight: "1",
}));

const iconClass = computed(() => props.icon || "");

const handleClick = (event: MouseEvent) => {
  event.stopPropagation();
  emit("click", event);
};

const handleDoubleClick = (event: MouseEvent) => {
  event.stopPropagation();
  emit("dblclick", event);
};

// 获取当前主题
const getCurrentTheme = (): "light" | "dark" => {
  return injectedEditorProps?.theme || 
    (document.querySelector("html")?.getAttribute("data-theme") === "dark" ? "dark" : "light");
};

// 更新 Tippy 主题
const updateTippyTheme = () => {
  buttonTippyInstance?.setProps({ theme: getCurrentTheme() });
};

// 初始化 Tippy 工具提示
const initTooltip = () => {
  if (!titleValue.value || !buttonRef.value) return;
  
  // 如果已存在实例，先销毁
  if (buttonTippyInstance) {
    buttonTippyInstance.destroy();
    buttonTippyInstance = null;
  }
  
  buttonTippyInstance = tippy(buttonRef.value, {
    content: titleValue.value,
    placement: "top",
    theme: getCurrentTheme(),
  });

  // 监听主题变化（只在首次创建时设置）
  if (!themeObserver) {
    const htmlElement = document.querySelector("html");
    if (htmlElement) {
      themeObserver = new MutationObserver(updateTippyTheme);
      themeObserver.observe(htmlElement, {
        attributes: true,
        attributeFilter: ["data-theme"],
      });
    }
  }
};

onMounted(() => {
  nextTick(initTooltip);
});

// 监听主题和标题变化
const stopThemeWatch = watch(() => injectedEditorProps?.theme, updateTippyTheme);
const stopTitleWatch = watch(titleValue, (newTitle) => {
  if (newTitle) {
    if (buttonTippyInstance) {
      buttonTippyInstance.setContent(newTitle);
    } else {
      nextTick(initTooltip);
    }
  }
});

// 清理所有资源
onBeforeUnmount(() => {
  // 停止 watch
  stopThemeWatch();
  stopTitleWatch();
  
  // 销毁 Tippy 实例
  if (buttonTippyInstance) {
    buttonTippyInstance.destroy();
    buttonTippyInstance = null;
  }
  
  // 断开 MutationObserver
  if (themeObserver) {
    themeObserver.disconnect();
    themeObserver = null;
  }
});

// 暴露按钮引用，供 Popover 等组件使用
defineExpose({
  buttonRef,
});
</script>

<style scoped>
.toolbar-button {
  margin: 0 2px;
  padding: 2px 4px;
  background: transparent;
  border: none;
  cursor: pointer;
  transition: all 0.1s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--editor-text-color);
  width: auto;
  height: auto;
  min-width: auto;
  min-height: auto;
}

.toolbar-button.is-active {
  background-color: var(--editor-button-active-background);
  color: var(--editor-text-color);
}

/* 只对包含图标或工具栏按钮图标的按钮应用 hover 背景色 */
.toolbar-button:not(.is-disabled):hover:has(.toolbar-button-icon),
.toolbar-button:not(.is-disabled):hover:has([class*="i-"]) {
  background-color: var(--editor-button-hover-background);
  color: var(--editor-text-color);
}

/* 对于包含自定义内容的按钮（如 heading-button-content），不应用 hover 背景色 */
.toolbar-button:not(.is-disabled):hover:has(.heading-button-content) {
  background-color: transparent;
}

/* 图标 hover 样式 */
.toolbar-button:not(.is-disabled) .toolbar-button-icon:hover {
  opacity: 0.8;
}

.toolbar-button.is-active:not(.is-disabled) .toolbar-button-icon:hover {
  opacity: 1;
}

.toolbar-button.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: var(--editor-text-color-disabled);
}

/* 图标+文字模式样式 */
.toolbar-button.has-label {
  /* min-width: 60px; */
}

.toolbar-button.has-label .toolbar-button-with-label {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/* 上下结构（ribbon 模式） */
.toolbar-button.has-label.label-vertical {
  flex-direction: column;
}

.toolbar-button.has-label.label-vertical .toolbar-button-with-label {
  flex-direction: column;
}

/* 左右结构（simple 模式） */
.toolbar-button.has-label.label-horizontal {
  flex-direction: row;
}

.toolbar-button.has-label.label-horizontal .toolbar-button-with-label {
  flex-direction: row;
  gap: 6px;
}

.toolbar-button.has-label .toolbar-button-icon {
  margin: 1px 0;
}

.toolbar-button.has-label .toolbar-button-label {
  font-size: var(--editor-font-size-small, 12px);
  line-height: 1.2;
  color: var(--editor-text-color);
  white-space: nowrap;
  user-select: none;
}

.toolbar-button.has-label.label-vertical .toolbar-button-label {
  text-align: center;
}

.toolbar-button.has-label.label-horizontal .toolbar-button-label {
  text-align: left;
}

.toolbar-button.is-large-icon .toolbar-button-icon {
  font-size: 24px;
  width: 24px;
  height: 24px;
}
</style>
